# 静态化首页
from collections import OrderedDict
import time
import os


from .models import ContentCategory
from meiduo_mall.apps.goods.models import GoodsChannel
from django.template import loader
from django.conf import settings


def generate_static_index_html():
    """
    生成静态的主页html文件
    """
    print('%s: generate_static_index_html' % time.ctime())
    # 查询所有的商品频道
    categories = OrderedDict()
    channels = GoodsChannel.objects.order_by('group_id', 'sequence')
    # 遍历所有的频道
    for channel in channels:
        # 获取当前频道所在的组 (多查一)
        group_id = channel.group_id  # 或者group_id = channel.group_id
        if group_id not in categories:
            categories[group_id] = {'channels': [], 'sub_cats': []}

        cat1 = channel.category  # 当前频道的类别, 一个频道对应一个一级类别

        # 追加当前频道
        categories[group_id]['channels'].append({
            'id': cat1.id,
            'name': cat1.name,
            'url': channel.url
        })
        # 构建当前类别的子类别
        for cat2 in cat1.subs.all():
            cat2.sub_cats = []  # 给二级类别添加一个保存三级类别数据的列表
            for cat3 in cat2.subs.all():
                cat2.sub_cats.append(cat3)
            categories[group_id]['sub_cats'].append(cat2)
    # print(categories)

    # 查询首页广告数据
    contents = {}
    # 查询所有广告类别数据
    content_categories = ContentCategory.objects.all()
    for cat in content_categories:
        contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')

    # 渲染模板的上下文
    context = {
        'categories': categories,
        'contents': contents
    }
    """渲染模板"""
    # 先获取模板文件
    template = loader.get_template('index.html')
    # 渲染首页html字符串
    html_text = template.render(context)
    # 将首页html字符串写入到指定目录，命名'index.html'
    file_path = os.path.join(settings.STATICFILES_DIRS[0], 'index.html')
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(html_text)


